package com.icloud.article.boot.service.impl;

import com.icloud.article.boot.dto.MarketGainersLosersPageDto;
import com.icloud.article.boot.service.MarketService;
import com.icloud.common.cache.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

@Slf4j
@Service
public class MarketServiceImpl implements MarketService {
    private String apiKey = "88bbddc1-63c6-4db4-8cd9-4889023babc1";
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisService redisService;

    @Override
    public String gainersLosers(MarketGainersLosersPageDto dto) {
        String url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/trending/gainers-losers";

        HttpHeaders headers = new HttpHeaders();
        headers.add("X-CMC_PRO_API_KEY", apiKey);
        headers.add("Accept", "application/json");
        headers.add("Accept-Encoding", "deflate, gzip");
        HttpEntity<String> entity = new HttpEntity<>(headers);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("start", dto.getStart());
        params.put("limit", dto.getLimit());
        params.put("time_period", dto.getTimePeriod());
        if(StringUtils.isNotBlank(dto.getConvert())) {
            params.put("convert", dto.getConvert());
        }
        if(StringUtils.isNotBlank(dto.getConvertId())) {
            params.put("convert_id", dto.getConvertId());
        }
        if(StringUtils.isNotBlank(dto.getSort())) {
            params.put("sort", dto.getSort());
        }
        if(StringUtils.isNotBlank(dto.getSortDir())) {
            params.put("sort_dir", dto.getSortDir());
        }

        // todo 当前账号的权限不足,不能得到正常报文.待升级
        ResponseEntity<byte[]> respString = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class, params);
        String resp = "";
        if (respString.getStatusCode() == HttpStatus.OK) {
            byte[] bodyBytes = respString.getBody();
            String contentEncoding = respString.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);
            if ("gzip".equals(contentEncoding)) { // gzip编码
                // gzip解压服务器的响应体
                byte[] data = new byte[0];
                try {
                    data = unGZip(new ByteArrayInputStream(bodyBytes));
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                    return resp;
                }
                resp = new String(data, StandardCharsets.UTF_8);
            } else {
                // TODO 其他的编码
            }
        }
        return resp;
    }

    private static byte[] unGZip(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream)) {
            byte[] buf = new byte[4096];
            int len = -1;
            while ((len = gzipInputStream.read(buf, 0, buf.length)) != -1) {
                byteArrayOutputStream.write(buf, 0, len);
            }
            return byteArrayOutputStream.toByteArray();
        } finally {
            byteArrayOutputStream.close();
        }
    }
}
